package com.xingkeduo.business.user.domain;

import com.xingkeduo.business.user.service.CraftsmanJobService;
import com.xingkeduo.business.user.service.CraftsmanService;
import com.xingkeduo.business.user.service.CraftsmanServiceService;
import com.xingkeduo.business.user.service.CraftsmanSocialService;
import com.xingkeduo.pojo.dto.BaseDTO;
import com.xingkeduo.pojo.dto.PriceDetailDto;
import com.xingkeduo.pojo.dto.PriceManagementDto;
import com.xingkeduo.pojo.dto.ShopServiceDTO;
import com.xingkeduo.pojo.enums.ServiceEnums;
import com.xingkeduo.pojo.query.CraftsmanJobQO;
import com.xingkeduo.pojo.query.CraftsmanQO;
import com.xingkeduo.pojo.query.CraftsmanServiceQO;
import com.xingkeduo.pojo.query.CraftsmanSocialQO;
import com.xingkeduo.pojo.table.CraftsmanJobTO;
import com.xingkeduo.pojo.table.CraftsmanServiceTO;
import com.xingkeduo.pojo.table.CraftsmanSocialTO;
import com.xingkeduo.pojo.table.CraftsmanTO;
import com.xingkeduo.pojo.utils.JsonUtils;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.IdentityUtil;
import com.xingkeduo.util.tool.IdentityUtil.Worker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务配置管理
 *
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/5/6 14:33
 **/
@Slf4j
@Component
public class ServiceDomain {

    @Autowired
    private CraftsmanServiceService craftsmanServiceService;
    @Autowired
    private CraftsmanService craftsmanService;
    @Autowired
    private FeignDomain feignDomain;
    @Autowired
    private CraftsmanJobService craftsmanJobService;
    @Autowired
    private CraftsmanSocialService craftsmanSocialService;

    private static int initListSize = 15;
//    private static int initMapSize = 16;

    /**
     * @desc： 根据门店id、服务类型获取对应的发型师及价格列表
     * @author: pantong
     * @date: 2019年5月8日 下午3:44:56
     */
    public List listCraftsmanPriceByShopIdAndServiceId(CraftsmanServiceQO craftsmanServiceQO) throws Throwable {
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(craftsmanServiceQO);
        return craftsmanServiceTOS;
    }


    /**
     * @desc：获取店铺下可约发型师中提供某个服务的发型师列表信息（含价格 价格取该店铺发型师配置的价格 如果没有配置返回空即可）pantong  2019年6月1日下午5:47:03
     * <p>
     * shopId 必填   serviceId必填  craftsmanId必填
     * @author: pantong
     * @date: 2019年5月8日 下午3:44:56
     */
    public List listCraftsmanInfoByShopIdAndServiceId(Long shopId, Long serviceId, String craftsmanIds) throws Throwable {
        //查询思路：先查询craftsmanIds中配置了该服务的发型师  2.遍历如果该店铺也配置了服务价格以该店铺的为准
        List<CraftsmanServiceTO> craftsmanServiceTOS = new ArrayList<CraftsmanServiceTO>();

        //1.查询craftsmanIds中配置了该服务的发型师
        CraftsmanServiceQO craftsmanServiceQO = new CraftsmanServiceQO();
        if (StringUtils.isNotEmpty(craftsmanIds)) {
            String[] craftsmanIdArr = craftsmanIds.split(",");
            if (craftsmanIdArr != null && craftsmanIdArr.length > 0) {
                List<Long> craftsmanIdList = new ArrayList<Long>();
                for (int i = 0; i < craftsmanIdArr.length; i++) {
                    if (StringUtils.isNotEmpty(craftsmanIdArr[i])) {
                        craftsmanIdList.add(Long.valueOf(craftsmanIdArr[i]));
                    }
                }
                if (craftsmanIdList != null && craftsmanIdList.size() > 0) {
                    craftsmanServiceQO.setCraftsmanIds(craftsmanIdList);
                } else {
                    return craftsmanServiceTOS;
                }
            }
        } else {
            return craftsmanServiceTOS;
        }
        if (serviceId != null) {
            craftsmanServiceQO.setServiceId(serviceId);
        } else {
            return craftsmanServiceTOS;
        }
        List<Long> shopIds = new ArrayList<Long>();
        shopIds.add(0L);
        craftsmanServiceQO.setShopIds(shopIds);
        craftsmanServiceQO.setIsDelete(YesNoEnum.NO);
        craftsmanServiceQO.setStatus(YesNoEnum.NO);
        craftsmanServiceTOS = craftsmanServiceService.selectByQuery(craftsmanServiceQO);
        if (craftsmanServiceTOS != null && craftsmanServiceTOS.size() > 0) {//craftsmanIds有提供该服务的发型师时  判断是否针对该店铺该服务配置了调价
            for (int i = 0; i < craftsmanServiceTOS.size(); i++) {
                if (craftsmanServiceTOS.get(i) != null && craftsmanServiceTOS.get(i).getCraftsmanId() > 0L) {
                    CraftsmanServiceQO craftsmanServiceQO1 = new CraftsmanServiceQO();
                    craftsmanServiceQO1.setCraftsmanId(craftsmanServiceTOS.get(i).getCraftsmanId());
                    craftsmanServiceQO1.setServiceId(serviceId);
                    craftsmanServiceQO1.setShopId(shopId);
                    craftsmanServiceQO1.setIsDelete(YesNoEnum.NO);
                    craftsmanServiceQO1.setStatus(YesNoEnum.NO);
                    List<CraftsmanServiceTO> ll = craftsmanServiceService.selectByQuery(craftsmanServiceQO1);
                    if (ll != null && ll.size() > 0 && ll.get(0).getPrices() != null && BigDecimal.ZERO.compareTo(ll.get(0).getPrices()) < 0) {
                        craftsmanServiceTOS.get(i).setPrices(ll.get(0).getPrices());
                    }
                }
            }
        }
        return craftsmanServiceTOS;
    }

    /**
     * 查询发型师服务配置详情
     *
     * @param serviceQO:
     * @return : 发型师服务技能，发型师价格，发型师门店
     * @author : gaozifeng
     * @date : 2019/5/16 10:07
     */
    public PriceDetailDto craftsmanServiceDetail(CraftsmanQO serviceQO) throws Throwable {
        if (0 == serviceQO.getId()) {
            throw new DataException(DataException.Type.DEFAULT, "发型师不能为空");
        }
        CraftsmanTO craftsmanTO = selectCraftsman(serviceQO);
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(craftsmanTO.getId()).setIsDelete(YesNoEnum.NO));
        if (null == craftsmanServiceTOS || craftsmanServiceTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "尚未配置服务技能");
        }
        //店铺信息
        BaseDTO shopInfo = null;
        if (craftsmanServiceTOS.get(0).getShopId() > 0) {
            shopInfo = feignDomain.getShopByKey(craftsmanServiceTOS.get(0).getShopId());
        }

        List<Long> serviceInfo = craftsmanServiceTOS.stream().filter(a -> a.getServiceId() > 0).map(a -> a.getServiceId()).collect(Collectors.toList());
        //发型师服务技能id，name
        List<BaseDTO> baseDTOList = null;
        if (serviceInfo.size() > 0) {
            String ids = JsonUtils.encodeParam("ids", serviceInfo);
            //服务列表
            baseDTOList = feignDomain.selectCraftsmanService(ids);
        }

        PriceDetailDto dto = new PriceDetailDto();
        dto.setCraftsmanId(craftsmanTO.getId());
        dto.setServiceList(baseDTOList.size() > 0 ? baseDTOList : null);
        dto.setShopInfo(shopInfo);
        return dto;
    }


    /**
     * 修改发型师服务技能
     *
     * @param craftsmanQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/6 14:40
     */
    @Transactional
    public void craftsmanUpdateService(CraftsmanQO craftsmanQO, CraftsmanServiceQO serviceQO) throws Throwable {
        CraftsmanTO craftsmanTO = selectCraftsman(craftsmanQO);
        //修改发型师绑定店铺
        if (0 != serviceQO.getShopId() && craftsmanTO.getStatus() == CraftsmanTO.Status.BIND) {
            updateShopId(craftsmanTO.getId(), serviceQO.getShopId());
        }
        List<Long> serviceIds = serviceQO.getServiceIds();
        craftsmanGetService(craftsmanTO);
        List<Long> list = new LinkedList<>();
        list.add(0L);
        //查询发型师的服务技能项
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(craftsmanTO.getId()).setShopIds(list).setIsDelete(YesNoEnum.NO));

        List<Long> selectServiceIds = craftsmanServiceTOS.stream().map(a -> a.getServiceId()).collect(Collectors.toList());
        boolean flag = false;
        if (serviceIds.size() != selectServiceIds.size()) {
            log.info("需要通知下单屏");
            flag = true;
        } else {
            for (Long selectIds : selectServiceIds) {
                if (serviceIds.contains(selectIds)) {
                    //通知夕桐
                    log.info("不需要通知下单屏技能id为" + serviceIds);
                } else {
                    log.info("需要通知下单屏");
                    flag = true;
                }
            }
        }

        if (flag) {
            if (null != craftsmanServiceTOS && craftsmanServiceTOS.size() > 0) {
                //服务技能id 集合
                List<CraftsmanServiceTO> updateList = craftsmanServiceTOS.stream().map(a -> a.setIsDelete(YesNoEnum.YES)).collect(Collectors.toList());
                int retVal = craftsmanServiceService.updateList(updateList);
                if (retVal != updateList.size()) {
                    throw new DataException(DataException.Type.DEFAULT, "修改服务技能失败");
                }
            }
            String encode = JsonUtils.encodeParam("ids", serviceQO.getServiceIds());
            List<BaseDTO> baseDTOS = feignDomain.selectCraftsmanService(encode);
            if (null == baseDTOS || baseDTOS.size() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "服务技能错误");
            }
            if (baseDTOS.size() < serviceQO.getServiceIds().size()) {
                throw new DataException(DataException.Type.DEFAULT, "服务技能不匹配");
            }
            //技能取消 发型师的服务技能取消  通知下单屏
            List<CraftsmanServiceTO> serviceList = craftsmanServiceTOS.stream().filter(item -> !serviceIds.stream().collect(Collectors.toList()).contains(item.getServiceId())).collect(Collectors.toList());
            if (null != serviceList && serviceList.size() > 0) {
                List<Long> serviceListIds = serviceList.stream().map(a -> a.getServiceId()).collect(Collectors.toList());
                List<CraftsmanServiceTO> updateServiceList = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setServiceIds(serviceListIds).setCraftsmanId(craftsmanTO.getId()).setIsDelete(YesNoEnum.NO));
                if (null != updateServiceList && updateServiceList.size() > 0) {
                    List<CraftsmanServiceTO> collect = updateServiceList.stream().map(a -> a.setIsDelete(YesNoEnum.YES)).collect(Collectors.toList());
                    int ret = craftsmanServiceService.updateList(collect);
                    if (ret != updateServiceList.size()) {
                        throw new DataException(DataException.Type.DEFAULT, "修改发型师技能失败");
                    }
                }
            }
            //没有配置过,批量新增
            List<CraftsmanServiceTO> insertList = new ArrayList<>();
            CraftsmanServiceTO serviceTO;
            for (int i = 0, j = serviceQO.getServiceIds().size(); i < j; i++) {
                serviceTO = new CraftsmanServiceTO();
                serviceTO.setIsDelete(YesNoEnum.NO).setCraftsmanId(craftsmanTO.getId()).setStuatus(YesNoEnum.NO)
                        .setServiceId(serviceQO.getServiceIds().get(i)).setId(IdentityUtil.nextId(Worker.USER)).setPrices(BigDecimal.ZERO);
                insertList.add(serviceTO);
            }
            craftsmanServiceService.insertList(insertList);
            //通知更改
            feignDomain.receiveStaffId(craftsmanTO.getId());
        }
    }

    /**
     * 修改发型师绑定门店
     *
     * @param craftsmanId:
     * @param shopId:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/5/22 20:22
     */
    private void updateShopId(long craftsmanId, long shopId) throws Throwable {
        CraftsmanJobTO jobTO = selectCraftsmanJobById(craftsmanId);
        if (jobTO.getShopId() != shopId) {
            log.info("修改发型师绑定店铺");
            jobTO.setShopId(shopId);
            craftsmanJobService.update(jobTO);
        } else {
            log.info("发型师的店铺相同");
        }

    }


    /**
     * 查询发型师，学员的服务技能显示
     *
     * @param craftsmanQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/6 15:43
     */
    public BaseDTO craftsmangetService(CraftsmanQO craftsmanQO) throws Throwable {
        CraftsmanTO craftsmanTO = selectCraftsman(craftsmanQO);

        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(craftsmanTO.getId()).setIsDelete(YesNoEnum.NO));
        if (null == craftsmanServiceTOS || craftsmanServiceTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "您现在暂未配置服务技能");
        } else {
            String encodeParam = JsonUtils.encodeParam("ids", craftsmanServiceTOS.stream().map(a -> a.getServiceId()).collect(Collectors.toList()));
            List<BaseDTO> baseDTOS = feignDomain.selectCraftsmanService(encodeParam);
            if (null == baseDTOS || baseDTOS.size() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "没有查询到服务技能");
            } else {
                String name = baseDTOS.stream().map(a -> a.getName()).collect(Collectors.joining("/"));
                BaseDTO baseDTO = new BaseDTO();
                baseDTO.setName(name);
                return baseDTO;
            }
        }
    }

    /**
     * 根据shopid serviceId 查询发型师价格，和列表
     *
     * @param serviceQO         门店 状态 服务           搜索条件
     * @param craftsmanJobQO    艺名和code
     * @param craftsmanSocialQO 姓名和code
     * @return :
     * @author : gaozifeng
     * @date : 2019/4/24 11:55
     */
    public List<PriceManagementDto> getCraftsmanInfoForList(CraftsmanServiceQO serviceQO, CraftsmanJobQO craftsmanJobQO, CraftsmanSocialQO craftsmanSocialQO, Page<PriceManagementDto> page) throws Throwable {
        //TODO 待优化代码
        Set<Long> ids = new HashSet<>();//名称昵称  code工号并集
        long id;
        if (StringUtils.isNotEmpty(craftsmanSocialQO.getName())) {
            //查询social  job 表
            List<Long> nickNameList = selectCraftsmanByJobName(craftsmanJobQO.getNickName());
            if (nickNameList != null && nickNameList.size() > 0) {
                log.info("job查询出来的艺名集合:" + nickNameList.toString());
                ids.addAll(nickNameList);
            }

            List<Long> nameList = selectCraftsmanSocialByName(craftsmanSocialQO.getName());
            if (nameList != null && nameList.size() > 0) {
                log.info("social查询出来的名字集合:" + nameList.toString());
                ids.addAll(nameList);
            }
        }
        if (0L != craftsmanJobQO.getCode()) {
            //搜索工号的
            id = selectCraftsmanJobByCode(craftsmanJobQO.getCode());
            if (id != 0L) {
                ids.add(id);
            }
        }
        if (StringUtils.isNotEmpty(craftsmanSocialQO.getName()) || 0L != craftsmanJobQO.getCode()) {
            if (ids == null || ids.size() <= 0)
                return Collections.emptyList();
        }

        if (0L != serviceQO.getShopId() || 0L != serviceQO.getServiceId()) {
            if (serviceQO.getShopId() <= 0) {
                serviceQO.setShopId(-1L);
            }
            List<CraftsmanServiceTO> serviceList;
            if (ids.size() > 0) {
                List<Long> selectIds = new ArrayList<>(ids);
                serviceList = craftsmanServiceService.selectByQuery(serviceQO.setIsDelete(YesNoEnum.NO).setCraftsmanIds(selectIds));
            } else {
                serviceList = craftsmanServiceService.selectByQuery(serviceQO.setIsDelete(YesNoEnum.NO));
            }
            if (null == serviceList || serviceList.size() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "没有数据");
            }
            List<Long> craftsmanIds = serviceList.stream().map(a -> a.getCraftsmanId()).collect(Collectors.toList());
            Set<Long> collect = craftsmanIds.stream().collect(Collectors.toSet());
            if (collect == null || collect.size() <= 0) {
                return Collections.emptyList();
            }
            ids = collect;
        }
        serviceQO.setGroupBy("craftsman_id,shop_id").setIsDelete(YesNoEnum.NO).setPrices("-1");
        if (ids.size() > 0) {
            List<Long> selectIds = new ArrayList<>(ids);
            serviceQO.setCraftsmanIds(selectIds);
        }
        page.init(craftsmanServiceService.selectCount(serviceQO));
        serviceQO.setRecordStart(page.getRecordStart()).setRecordEnd(page.getRecordEnd()).setOrderBy("updatedtime desc");
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(serviceQO);

        if (null == craftsmanServiceTOS || craftsmanServiceTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "没有查询到数据");
        }
        List<Long> craftsmanIds = craftsmanServiceTOS.stream().map(a -> a.getCraftsmanId()).collect(Collectors.toList());
        List<Long> shopIds = craftsmanServiceTOS.stream().map(a -> a.getShopId()).collect(Collectors.toList());
        List<CraftsmanJobTO> jobList = craftsmanJobService.selectByQueryForShopId(new CraftsmanJobQO().setIds(craftsmanIds));
        if (null == jobList || jobList.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "没有查询到发型师记录");
        }
        List<CraftsmanSocialTO> socialList = craftsmanSocialService.selectByQuery(new CraftsmanSocialQO().setIds(craftsmanIds));
        Map<String, BaseDTO> shopMap = null;
        //查找表中 大于0的shopid 列表
        List<Long> collect = shopIds.stream().filter(a -> a > 0).collect(Collectors.toList());
        if (collect.size() > 0) {
            String encode = JsonUtils.encodeParam("ids", shopIds);
            //多个员工会在一家门店下    shop集合
            List<BaseDTO> shopForList = feignDomain.getShopForList(encode);
            //外部店铺的shopid作为key
            shopMap = shopForList.stream().collect(Collectors.toMap(BaseDTO::getId, a -> a, (k1, k2) -> k2));
        }
        List<Long> craftsmanListIds = jobList.stream().filter(a -> a.getId() > 0).map(a -> a.getId()).collect(Collectors.toList());

        List<CraftsmanTO> craftsman = craftsmanService.selectByQuery(new CraftsmanQO().setIds(craftsmanListIds).setIsDelete(YesNoEnum.NO));

        Map<Long, CraftsmanTO> craftsmanMap = craftsman.stream().collect(Collectors.toMap(CraftsmanTO::getId, a -> a, (k1, k2) -> k1));

        //return
        List<PriceManagementDto> list = new ArrayList<>(initListSize);
        //查询发型师的名称 用key
        Map<Long, CraftsmanJobTO> jobMap = jobList.stream().collect(Collectors.toMap(CraftsmanJobTO::getId, a -> a, (k1, k2) -> k1));
        //查询发型师的艺名 用key
        Map<Long, CraftsmanSocialTO> socialMap = socialList.stream().collect(Collectors.toMap(CraftsmanSocialTO::getId, a -> a, (k1, k2) -> k1));

        for (int i = 0, j = craftsmanServiceTOS.size(); i < j; i++) {
            BigDecimal prices = craftsmanServiceTOS.get(i).getPrices();
            if (prices.compareTo(BigDecimal.ZERO) == 0) {
                break;
            }
            PriceManagementDto dto = new PriceManagementDto();
            CraftsmanJobTO craftsmanJobTO = jobMap.get(craftsmanServiceTOS.get(i).getCraftsmanId());
            if (null == craftsmanJobTO) {
                log.info("发型师id为空------调价id[{}]----continue----", craftsmanServiceTOS.get(i).getId());
                continue;
            }
            dto.setId(craftsmanJobTO.getId());
            CraftsmanTO craftsmanTO = craftsmanMap.get(craftsmanServiceTOS.get(i).getCraftsmanId());
            if (null != craftsmanTO) {
                dto.setCode(craftsmanTO.getCode());
            }
            if (collect.size() > 0) {
                BaseDTO baseDTO = shopMap.get(String.valueOf(craftsmanServiceTOS.get(i).getShopId()));
                if (null == baseDTO) {
                    log.info("没有发现门店[{}]", craftsmanServiceTOS.get(i).getShopId());
                    continue;
                }
                log.info("获取shopName----------------" + (null == baseDTO ? null : baseDTO.getName()));
                //门店name
                dto.setShopName(null == baseDTO ? null : baseDTO.getName());
                //门店id
                dto.setShopId((null == baseDTO) ? null : baseDTO.getId());
                CraftsmanSocialTO socialTO = socialMap.get(dto.getId());
                if (null != socialTO && null != socialTO.getName()) {
                    //服务名字
                    dto.setName(socialTO.getName() == null ? null : socialTO.getName());
                }
                dto.setLeavelType(craftsmanTO.getStatus().getValue());
                CraftsmanJobTO jobTO = jobMap.get(dto.getId());
                if (null != jobTO && null != jobTO.getNickName()) {
                    //艺名
                    dto.setNickName(jobTO.getNickName() == null ? null : jobTO.getNickName());
                }
                //状态和修改时间
                if (null != craftsmanServiceTOS.get(i)) {
                    if (null != craftsmanServiceTOS.get(i).getStatus())
                        dto.setStatus(craftsmanServiceTOS.get(i).getStatus());
                    dto.setUpdateDate(craftsmanServiceTOS.get(i).getUpdatedTime());
                }

                List<CraftsmanServiceTO> craftsmanInfoServiceList = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setShopId(Long.parseLong(dto.getShopId())).setCraftsmanId(dto.getId()).setIsDelete(YesNoEnum.NO));
                //调价信息
                if (null != craftsmanInfoServiceList && craftsmanInfoServiceList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (CraftsmanServiceTO service : craftsmanInfoServiceList) {
                        if (dto.getId() == service.getCraftsmanId()) {
                            if (("1").equals(String.valueOf(service.getServiceId()))) {
                                sb.append(ServiceEnums.SINGLE_HAIRCUT.getName());
                                sb.append("/");
                            } else if (("2").equals(String.valueOf(service.getServiceId()))) {
                                sb.append(ServiceEnums.SINGLE_LIUHAI.getName());
                                sb.append("/");
                            } else if (("4").equals(String.valueOf(service.getServiceId()))) {
                                sb.append(ServiceEnums.SINGLE_BABEER.getName());
                                sb.append("/");
                            } else if (("5").equals(String.valueOf(service.getServiceId()))) {
                                sb.append(ServiceEnums.SINGLE_REDUCTION.getName());
                                sb.append("/");
                            } else if (("6").equals(String.valueOf(service.getServiceId()))) {
                                sb.append(ServiceEnums.SINGLE_BABEER_HALF.getName());
                                sb.append("/");
                            }
                        }
                    }
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1);
                    }
                    dto.setPriceInfo(sb.toString());
                }
            }
            list.add(dto);
        }
        page.setDtoList(list);
        return list;
    }


    /**
     * 新增查询店铺和发型师服务交集
     *
     * @param serviceQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/17 10:20
     */
    public BaseDTO getPriceMixed(CraftsmanServiceQO serviceQO) throws Throwable {

        //门店服务技能
        List<ShopServiceDTO> shopServicePriceByShopId = feignDomain.getShopServicePriceByShopId(serviceQO.getShopId());
        //查询发型师服务技能
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(serviceQO.getCraftsmanId()).setIsDelete(YesNoEnum.NO));
        if (null == craftsmanServiceTOS || craftsmanServiceTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师还未配置服务项");
        }
        Map<Long, CraftsmanServiceTO> serviceMap = craftsmanServiceTOS.stream().collect(Collectors.toMap(CraftsmanServiceTO::getServiceId, a -> a, (k1, k2) -> k1));
        //发型师服务name信息
        BaseDTO baseDTO = craftsmangetService(new CraftsmanQO().setId(serviceQO.getCraftsmanId()));
        //交集
        List<ShopServiceDTO> returnList = new ArrayList<>(initListSize);
        //门店 价格信息
        //门店服务name
        List<String> shopName = shopServicePriceByShopId.stream().peek(a -> {
            //获取当前服务id
            log.info("获取当前服务id-----" + a);
            log.info("服务map 获取当前发型师服务技能信息-----" + serviceMap.get(a.getServprodId()));
            CraftsmanServiceTO serviceTO = serviceMap.get(a.getServprodId());
            if (null != serviceTO && 0 != serviceTO.getServiceId()) {
                log.info("获取当前服务不能为空-----" + serviceTO.toString());
                ShopServiceDTO dto = new ShopServiceDTO();
                dto.setShopsId(a.getShopsId());
                dto.setServprodId(a.getServprodId());
                dto.setServprodName(a.getServprodName());
                returnList.add(dto);
            }
        }).filter(c -> null != c.getServprodName()).map(c -> c.getServprodName() + "/").collect(Collectors.toList());
        if (returnList.size() == 0) {
            log.info("发型师和门店没有服务交集" + returnList.size());
            throw new DataException(DataException.Type.DEFAULT, "没有查询到门店和发型师匹配的服务技能");
        }
        baseDTO.setValue(shopName.toString());
        baseDTO.setShopsServprodList(returnList);
        return baseDTO;
    }


    /**
     * 外部接口---发型师集合的服务技能
     *
     * @param craftsmanIds:
     * @return : com.xingkeduo.pojo.dto.BaseDTO
     * @author : gaozifeng
     * @date : 2019/6/3 14:49
     */
    public List<BaseDTO> getCraftsmanServiceForList(List<Long> craftsmanIds) throws Throwable {
        log.info("查询发型师服务技能---多条数据");
        if (null == craftsmanIds || craftsmanIds.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师参数不能为空");
        }
        //配置了服务技能，但是没有配置调价  小程序用户进来 该发型师会展示门店下面 该服务技能的默认价格
        List<CraftsmanServiceTO> serviceTOList = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanIds(craftsmanIds).setStatus(YesNoEnum.NO).setIsDelete(YesNoEnum.NO).setShopId(0L));
        if (null == serviceTOList || serviceTOList.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师还未配置服务项");
        }
        List<BaseDTO> returnList = new LinkedList<>();
        for (Long id : craftsmanIds) {
            Set<Long> serviceIds = new HashSet<>(initListSize);
            //发型师信息
            BaseDTO dto = new BaseDTO();
            for (CraftsmanServiceTO serviceTO : serviceTOList) {
                if (serviceTO.getCraftsmanId() == id) {
                    //id
                    dto.setCraftsmanId(id);
                    //服务集合
                    serviceIds.add(serviceTO.getServiceId());
                }
            }
            //设置服务集合
            List<Long> list = new LinkedList<>(serviceIds);
            dto.setServiceIds(list);
            returnList.add(dto);
        }
        return returnList;
    }

    /**
     * 编辑查询店铺和发型师服务交集
     *
     * @param serviceQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/17 10:20
     */
    public BaseDTO updateGetPriceMixed(CraftsmanServiceQO serviceQO) throws Throwable {
        if (0L == serviceQO.getShopId() || 0L == serviceQO.getCraftsmanId()) {
            throw new DataException(DataException.Type.DEFAULT, "门店和发型师信息不能为空");
        }
//        String id = JsonUtils.encodeParam("id", serviceQO.getShopId());
        //门店服务信息
        List<ShopServiceDTO> shopServicePriceByShopId = feignDomain.getShopServicePriceByShopId(serviceQO.getShopId());
        //查询发型师服务技能
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(serviceQO.getCraftsmanId()).setIsDelete(YesNoEnum.NO));
        if (null == craftsmanServiceTOS || craftsmanServiceTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师还未配置服务项");
        }
        //查询发型师和店铺的信息
        List<CraftsmanServiceTO> shopList = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(serviceQO.getCraftsmanId()).setPrices("-1").setShopId(serviceQO.getShopId()).setIsDelete(YesNoEnum.NO));
        if (shopList.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "没有查询到匹配的价格信息");
        }
        //服务id 作为key
        Map<Long, CraftsmanServiceTO> serviceMap = craftsmanServiceTOS.stream().collect(Collectors.toMap(CraftsmanServiceTO::getServiceId, a -> a, (k1, k2) -> k1));
        Map<Long, CraftsmanServiceTO> craftsmanShopMap = shopList.stream().collect(Collectors.toMap(CraftsmanServiceTO::getServiceId, a -> a, (k1, k2) -> k1));

        //发型师服务name信息
        BaseDTO baseDTO = craftsmangetService(new CraftsmanQO().setId(serviceQO.getCraftsmanId()));
        //交集
        List<ShopServiceDTO> returnList = new ArrayList<>(initListSize);
        //门店 价格信息
        //门店服务name
        List<String> shopName = shopServicePriceByShopId.stream().peek(a -> {
            //获取当前服务id
            log.info("获取当前服务id-----" + a);
            log.info("服务map 获取当前发型师服务技能信息-----" + serviceMap.get(a.getServprodId()));
            CraftsmanServiceTO serviceTO = serviceMap.get(a.getServprodId());
            CraftsmanServiceTO shopTO = craftsmanShopMap.get(a.getServprodId());
            if (null != serviceTO && 0 != serviceTO.getServiceId()) {
                log.info("获取当前服务不为空-----" + serviceTO.toString());
                ShopServiceDTO dto = new ShopServiceDTO();
                dto.setShopsId(a.getShopsId());
                dto.setServprodId(a.getServprodId());
                if (null != shopTO) {
                    dto.setPrice(("0.0").equals(String.valueOf(shopTO.getPrices())) ? "0.0" : String.valueOf(shopTO.getPrices()));
                }
                dto.setServprodName(null == a.getServprodName() ? null : a.getServprodName());
                returnList.add(dto);
            }
        }).filter(c -> null != c.getServprodName()).map(c -> c.getServprodName() + "/").collect(Collectors.toList());
        if (returnList.size() == 0) {
            log.info("发型师和门店没有服务交集" + returnList.size());
            throw new DataException(DataException.Type.DEFAULT, "没有查询到门店和发型师匹配的服务技能");
        }
        baseDTO.setValue(shopName.toString());
        baseDTO.setShopsServprodList(returnList);
        return baseDTO;
    }

    /**
     * 新增调价
     *
     * @param primary:
     * @param serviceQO:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/5/6 21:58
     */
    @Transactional
    public void insertPrice(CraftsmanQO primary, CraftsmanServiceQO serviceQO) throws Throwable {
        CraftsmanTO craftsmanById = selectCraftsman(primary);
        craftsmanGetService(craftsmanById);
        List<BaseDTO> serviceList = serviceQO.getServiceList();
        if (null == serviceList || serviceList.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "服务不能为空");
        }
        //查询发型师的服务技能
        List<CraftsmanServiceTO> serviceTOList = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(craftsmanById.getId()).setIsDelete(YesNoEnum.NO).setStatus(YesNoEnum.NO));
        if (null != serviceTOList && serviceTOList.size() > 0) {
            String encode = JsonUtils.encodeParam("ids", serviceList.stream().map(a -> Long.parseLong(a.getId())).collect(Collectors.toList()));
            //查出来的
            List<BaseDTO> baseDTOS = feignDomain.selectCraftsmanService(encode);
            if (null == baseDTOS || baseDTOS.size() <= 0) {
                throw new DataException(DataException.Type.DEFAULT, "服务没有匹配成功");
            }
            if (baseDTOS.size() < serviceList.size()) {
                throw new DataException(DataException.Type.DEFAULT, "传入服务错误");
            }
            List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setShopId(serviceQO.getShopId()).setCraftsmanId(serviceQO.getCraftsmanId()).setIsDelete(YesNoEnum.NO).setPrices("-1"));
            if (null != craftsmanServiceTOS && craftsmanServiceTOS.size() > 0) {
                throw new DataException(DataException.Type.DEFAULT, "您已经配置过该门店价格");
            }
            List<BaseDTO> requesetServiceList = serviceQO.getServiceList();
            log.info("传过来的服务list" + requesetServiceList);
            //传来的服务技能 和价格
            List<CraftsmanServiceTO> list = new ArrayList<>(initListSize);
            for (int i = 0; i < serviceQO.getServiceList().size(); i++) {
                CraftsmanServiceTO serviceTO = new CraftsmanServiceTO();
                BaseDTO baseDTO = serviceQO.getServiceList().get(i);
                BigDecimal bigDecimal = new BigDecimal(baseDTO.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP);
                serviceTO.setId(IdentityUtil.nextId(Worker.USER)).setShopId(serviceQO.getShopId()).setCraftsmanId(serviceQO.getCraftsmanId()).setServiceId(Long.parseLong(baseDTO.getId()))
                        .setPrices(bigDecimal).setStuatus(YesNoEnum.NO).setIsDelete(YesNoEnum.NO);
                list.add(serviceTO);
            }
            if (list.size() > 0) {
                craftsmanServiceService.insertList(list);
                //通知更改
                feignDomain.receiveStaffId(craftsmanById.getId());
            }
        } else {
            throw new DataException(DataException.Type.DEFAULT, "您还未配置服务项目");
        }
    }

    /**
     * 编辑店铺调价
     *
     * @param :
     * @return : void
     * @author : gaozifeng
     * @date : 2019/5/20 14:20
     */
    @Transactional
    public void updatePrice(CraftsmanQO primary, CraftsmanServiceQO serviceQO) throws Throwable {
        CraftsmanTO craftsmanById = selectCraftsman(primary);
        craftsmanGetService(craftsmanById);
        //要编辑或者新增的服务
        List<BaseDTO> serviceList = serviceQO.getServiceList();
        if (null == serviceList || serviceList.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "服务不能为空");
        }
        String encode = JsonUtils.encodeParam("ids", serviceList.stream().map(a -> Long.parseLong(a.getId())).collect(Collectors.toList()));
        //查出来的
        List<BaseDTO> baseDTOS = feignDomain.selectCraftsmanService(encode);
        if (null == baseDTOS || baseDTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "服务没有匹配成功");
        }
        if (baseDTOS.size() < serviceList.size()) {
            throw new DataException(DataException.Type.DEFAULT, "传入服务错误");
        }
        //传来的服务id
        List<Long> serviceIds = serviceList.stream().map(a -> Long.parseLong(a.getId())).collect(Collectors.toList());

        //修改 查询是否有此店铺的信息
        List<CraftsmanServiceTO> serviceTOList = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO().setCraftsmanId(craftsmanById.getId()).setPrices("-1").setShopId(serviceQO.getShopId()).setIsDelete(YesNoEnum.NO));

        if (null != serviceTOList && serviceTOList.size() > 0) {
            //删除isdelete  不改变状态
            boolean flag = false;

            List<Long> selectIds = serviceTOList.stream().map(a -> a.getServiceId()).collect(Collectors.toList());
            //服务id为key 的当前发型师服务信息
            Map<Long, CraftsmanServiceTO> map = serviceTOList.stream().collect(Collectors.toMap(CraftsmanServiceTO::getServiceId, a -> a, (k1, k2) -> k1));
            //修改的服务id和价格
            Map<String, BaseDTO> reqestParamMap = serviceList.stream().collect(Collectors.toMap(BaseDTO::getId, a -> a, (k1, k2) -> k1));

            if (serviceTOList.size() != serviceIds.size()) {
                flag = true;
                log.info("updatePrice-----发型师的服务技能，没有修改");
            } else {
                for (Long requestId : serviceIds) {
                    if (selectIds.contains(requestId)) {
                        CraftsmanServiceTO serviceTO = map.get(requestId);

                        BaseDTO baseDTO = reqestParamMap.get(String.valueOf(requestId));

                        BigDecimal bigDecimal = new BigDecimal(baseDTO.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP);
                        if (bigDecimal.equals(serviceTO.getPrices())) {
                            log.info("updatePrice-----发型师的服务价格，没有修改");
                        } else {
                            log.info("updatePrice-----发型师的价格 更改,然后通知夕桐");
                            flag = true;
                            break;
                        }
                    } else {
                        log.info("updatePrice------发型师的服务更改,然后通知夕桐");
                        flag = true;
                        break;
                    }
                }
            }


            if (flag) {

                int checkStatus = 0;
                for (int i = 0; i < serviceTOList.size(); i++) {
                    //如果是生效的编辑
                    if (serviceTOList.get(i).getStatus() == YesNoEnum.NO) {
                        checkStatus = 1;
                    }
                    //统一修改失效和删除
                    serviceTOList.get(i).setStuatus(YesNoEnum.YES).setIsDelete(YesNoEnum.YES);
                }
                int retVal = craftsmanServiceService.updateList(serviceTOList);
                if (retVal != serviceTOList.size()) {
                    throw new DataException(DataException.Type.DEFAULT, "修改调价失败");
                }
                List<CraftsmanServiceTO> list = new ArrayList<>(initListSize);
                for (int i = 0; i < serviceQO.getServiceList().size(); i++) {
                    CraftsmanServiceTO serviceTO = new CraftsmanServiceTO();
                    BaseDTO baseDTO = serviceQO.getServiceList().get(i);
                    BigDecimal bigDecimal = new BigDecimal(baseDTO.getValue()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    serviceTO.setId(IdentityUtil.nextId(Worker.USER)).setShopId(serviceQO.getShopId()).setCraftsmanId(serviceQO.getCraftsmanId()).setServiceId(Long.parseLong(baseDTO.getId()))
                            .setPrices(bigDecimal).setIsDelete(YesNoEnum.NO);
                    //失效的
                    if (checkStatus == 1) {
                        serviceTO.setStuatus(YesNoEnum.NO);
                    } else {
                        serviceTO.setStuatus(YesNoEnum.YES);
                    }
                    list.add(serviceTO);
                }
                if (list.size() > 0) {
                    craftsmanServiceService.insertList(list);
                }
                //通知更改
                if (checkStatus == 1) {
                    log.info("生效状态编辑调价通知,发型师id[{}]", craftsmanById.getId());
                    feignDomain.receiveStaffId(craftsmanById.getId());
                }
            }
        } else {
            throw new DataException(DataException.Type.DEFAULT, "该发型师和门店的调价信息，已经存在，无法再创建");
        }
    }

    /**
     * 门店发型师价格失效/生效     查询列表  查看 isdelete =0 and status =0
     * isdelete 是删除   status 1生效  0失效
     *
     * @param craftsmanServiceQO:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/5/7 15:54
     */
    @Transactional
    public void craftsmanServiceOutOrEff(CraftsmanQO craftsmanQO, CraftsmanServiceQO craftsmanServiceQO) throws
            Throwable {
        CraftsmanTO craftsmanTO = selectCraftsman(craftsmanQO);
        craftsmanGetService(craftsmanTO);
        List<CraftsmanServiceTO> craftsmanServiceTOS = craftsmanServiceService.selectByQuery(new CraftsmanServiceQO()
                .setCraftsmanId(craftsmanQO.getId()).setShopId(craftsmanServiceQO.getShopId()).setIsDelete(YesNoEnum.NO));
        if (null == craftsmanServiceTOS || craftsmanServiceTOS.size() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师没有服务技能");
        }
        YesNoEnum yesNoEnum = craftsmanServiceTOS.stream().findFirst().map(CraftsmanServiceTO::getStatus).orElse(null);
        List<CraftsmanServiceTO> collect = null;
        if (null == yesNoEnum) {
            throw new DataException(DataException.Type.DEFAULT, "状态错误");
        } else if (yesNoEnum == YesNoEnum.NO) {
            //修改为失效
            collect = craftsmanServiceTOS.stream().map(a -> a.setStuatus(YesNoEnum.YES)).collect(Collectors.toList());
        } else if (yesNoEnum == YesNoEnum.YES) {
            collect = craftsmanServiceTOS.stream().map(a -> a.setStuatus(YesNoEnum.NO)).collect(Collectors.toList());
        }
        //只设置状态,后面可以恢复
        int retVal = craftsmanServiceService.updateList(collect);
        if (retVal != collect.size()) {
            throw new DataException(DataException.Type.DEFAULT, "修改失效失败.");
        }
        //通知更改
        log.info("生效/失效更改,发型师id[{}]", craftsmanTO.getId());
        feignDomain.receiveStaffId(craftsmanTO.getId());
    }


    /**
     * 获取发型师
     *
     * @param craftsmanQO:
     * @return : com.xingkeduo.pojo.table.CraftsmanTO
     * @author : gaozifeng
     * @date : 2019/5/6 14:38
     */
    private CraftsmanTO selectCraftsman(CraftsmanQO craftsmanQO) throws Throwable {
        CraftsmanTO craftsmanTO = craftsmanService.selectByPrimary(craftsmanQO.getId());
        if (null == craftsmanTO || craftsmanTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师不存在");
        }
        return craftsmanTO;
    }

    /**
     * 获取发型师工作信息
     *
     * @param id:
     * @return : com.xingkeduo.pojo.table.CraftsmanJobTO
     * @author : gaozifeng
     * @date : 2019/5/16 10:13
     */
    private CraftsmanJobTO selectCraftsmanJobById(long id) throws Throwable {
        CraftsmanJobTO jobTO = craftsmanJobService.selectByPrimary(id);
        if (null == jobTO || jobTO.getId() <= 0) {
            throw new DataException(DataException.Type.DEFAULT, "发型师信息不存在");
        }
        return jobTO;
    }

    /**
     * 获取发型师工作信息
     *
     * @param
     * @return : 返回id
     * @author : gaozifeng
     * @date : 2019年5月18日11:57:04
     */
    private long selectCraftsmanJobByCode(long code) throws Throwable {
        CraftsmanTO craftsmanTO = craftsmanService.selectByCode(code);
        if (null != craftsmanTO && craftsmanTO.getId() > 0L) {
            return craftsmanTO.getId();
        }
        return 0L;
    }

    /**
     * 获取发型师工作信息
     *
     * @param
     * @return : 返回id
     * @author : gaozifeng
     * @date : 2019年5月18日11:57:04
     */
    private List<Long> selectCraftsmanByJobName(String nickName) throws Throwable {
        List<Long> list = craftsmanJobService.selectByNickName(nickName);
        log.info("调价管理---搜索Job艺名" + list.toString());
        return list;
    }

    /**
     * 获取发型师工作信息
     *
     * @param
     * @return : 返回id
     * @author : gaozifeng
     * @date : 2019年5月18日11:57:04
     */
    private List<Long> selectCraftsmanSocialByName(String name) throws Throwable {
        List<Long> list = craftsmanSocialService.selectByName(name);
        log.info("调价管理---搜索Social名字" + list.toString());
        return list;
    }

    /**
     * 发型师服务技能/调价
     *
     * @param craftsmanTO:
     * @return : void
     * @author : gaozifeng
     * @date : 2019/5/6 14:39
     */
    private void craftsmanGetService(CraftsmanTO craftsmanTO) {
        if (craftsmanTO.getStatus() != CraftsmanTO.Status.FLOW && craftsmanTO.getStatus() != CraftsmanTO.Status.BIND && craftsmanTO.getStatus() != CraftsmanTO.Status.STUDENT) {
            throw new DataException(DataException.Type.DEFAULT, "您已离职");
        }
    }
}
